from app01 import models
from django import forms
from app01.utils.Bootstrap import BootStrapModelForm

class UserModelFrom(BootStrapModelForm):
    name = forms.CharField(min_length=3, label="用户名",widget=forms.TextInput(attrs={"class":"form-control"}))

    class Meta:
        model = models.Userinfo
        fields = ["name", "password", "age", "account", "create_time", "gender", "depart"]
        widgets = {
            "password": forms.PasswordInput(render_value=True)
        }

"""新建靓号"""
# 验证:方式1
from django.core.validators import RegexValidator
# 验证:方式2
from django.core.exceptions import ValidationError


class PrettyModelFrom(BootStrapModelForm):
    # 验证:方式一
    mobile = forms.CharField(
        label='手机号',
        validators=[RegexValidator(r'^1[3-9]\d{9}$', '手机号格式错误！')]
    )

    class Meta:
        model = models.PrettyNum
        fields = ["mobile", "price", "level", "status"]
        # 使用所有字段
        # fields = "__all__"
        # 排除那个字段,其他的全都带
        # exclude = ['level']

    # 验证:方式2
    def clean_mobile(self):
        # 获取用户传入的数据
        txt_mobile = self.cleaned_data["mobile"]
        exists = models.PrettyNum.objects.filter(mobile=txt_mobile).exists()
        if exists:
            # 验证不通过
            raise ValidationError("手机号已存在！")
        # 验证通过
        return txt_mobile

class PrettyEditModelFrom(forms.ModelForm):
    # mobile = forms.CharField(disabled=True, label='手机号')
    mobile = forms.CharField(
        label='手机号',
        validators=[RegexValidator(r'^1[3-9]\d{9}$', '手机号格式错误！')]
    )

    class Meta:
        model = models.PrettyNum
        fields = ["mobile", "price", "level", "status"]
        # 使用所有字段
        # fields = "__all__"
        # 排除那个字段,其他的全都带
        # exclude = ['level']

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for name, field in self.fields.items():
            # if name==password:
            #     continue
            field.widget.attrs = {"class": "form-control", "placeholder": field.label}

    def clean_mobile(self):
        # 获取用户传入的数据
        txt_mobile = self.cleaned_data["mobile"]
        # 不允许和其他号码相同，先排除自己，再判断
        exists = models.PrettyNum.objects.exclude(id=self.instance.pk).filter(mobile=txt_mobile).exists()
        if exists:
            # 验证不通过
            raise ValidationError("手机号已存在！")
        # 验证通过
        return txt_mobile